package com.miraclesea.webmvc.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.miraclesea.framework.dao.exception.DataIntegrityViolationException;
import com.miraclesea.webmvc.vo.BaseResponse;
import com.miraclesea.webmvc.vo.ResponseFeedback;

public abstract class AsyncBaseMangementController<T> {
	
	public final ResponseEntity<BaseResponse<T>> add(final T entity, final BindingResult result, final MvcCallback callback) {
		BaseResponse<T> response = new BaseResponse<T>();
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				response.getErrors().add(ResponseFeedback.builder().code(error.getCodes()[0]).build());
			}
			return new ResponseEntity<BaseResponse<T>>(response, HttpStatus.UNPROCESSABLE_ENTITY);
		}
		try {
			callback.execute();
		} catch (final DataIntegrityViolationException ex) {
			response.getErrors().add(ResponseFeedback.builder().code(ex.getKey()).build());
			return new ResponseEntity<BaseResponse<T>>(response, HttpStatus.CONFLICT);
		}
		return new ResponseEntity<BaseResponse<T>>(response, HttpStatus.CREATED);
	}
	
}
